package LeetCode;

import java.util.Arrays;

/**
 * 611. 有效三角形的个数
 * https://leetcode.cn/problems/valid-triangle-number/description/
 */
class Solution3 {
    //利用单调性，双指针的算法解决问题
    public int triangleNumber(int[] nums) {
        //先给数组排序
        Arrays.sort(nums);
        //计数器
        int count = 0;
        for(int i = nums.length - 1; i >= 2; i--) {
            //定义左右节点
            int left = 0, right = i - 1;
            int c = nums[i];
            while(left < right) {
                if(nums[left] + nums[right] > c) {
                    count += right - left;
                    right--;
                } else {
                    //nums[left] + nums[right] <= c
                    left++;
                }
            }
        }
        return count;
    }
}